package com.sinochem.yunlian.ship.common.mq;

import com.sinochem.yunlian.ship.common.exception.RocketMQException;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RocketMQProducerConfiguration {

	public static final Logger LOGGER = LoggerFactory.getLogger(RocketMQProducerConfiguration.class);

	@Value("${rocketmq.namesrvAddr:#{null}}")
	private String namesrvAddr;
	@Value("${rocketmq.producer.groupName:#{null}}")
	private String groupName;
	@Value("${rocketmq.producer.maxMessageSize:4194304}")  //4194304= 4M =1024 * 1024 * 4;
	private int maxMessageSize;
	@Value("${rocketmq.producer.sendMsgTimeout:3000}")
	private int sendMsgTimeout;

	@Bean
	public DefaultMQProducer defaultProducer() throws RocketMQException {
		if (StringUtils.isBlank(this.groupName)) {
			return null;
		}
		if (StringUtils.isBlank(this.namesrvAddr)) {
			return null;
		}

		DefaultMQProducer producer = new DefaultMQProducer(this.groupName);
		producer.setNamesrvAddr(this.namesrvAddr);
		//producer.setInstanceName(instanceName);
		producer.setMaxMessageSize(this.maxMessageSize);
		producer.setSendMsgTimeout(this.sendMsgTimeout);
		producer.setVipChannelEnabled(false);
		try {
			producer.start();
			LOGGER.info(String.format("producer is start ! groupName:[%s],namesrvAddr:[%s]", this.groupName,
					this.namesrvAddr));
		} catch (MQClientException e) {
			LOGGER.error(String.format("producer is error {}", e.getMessage(), e));
			throw new RocketMQException(e);
		}
		return producer;
	}

}
